﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;

namespace Ycjw.PipeLine.Commons
{
    public static class MethodExtensions
    {
        /// <summary>
        /// 获取属性值
        /// </summary>
        /// <param name="obj">对象</param>
        /// <param name="property">属性</param>
        /// <returns></returns>
        public static object GetPropertyValue(this object obj, string property)
        {
            try
            {
                if (obj == null)
                {
                    return null;
                }
                if (string.IsNullOrEmpty(property))
                {
                    return null;
                }
                // 获取属性
                PropertyInfo propertyInfo = obj.GetType().GetProperty(property);
                if (propertyInfo == null)
                {
                    return null;
                }
                // 返回值
                return propertyInfo.GetValue(obj, null);
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("反射获取对象字段值异常 GetPropertyValue,obj:{0}\r\n property{1} ", obj.ToString(), property), ex);
            }
        }

        /// <summary>
        /// 设置对象属性值
        /// </summary>
        /// <param name="obj"对象></param>
        /// <param name="property">属性</param>
        /// <param name="value">值</param>
        public static void SetPropertyValue(this object obj, string property, object value)
        {
            try
            {
                PropertyInfo propertyInfo = obj.GetType().GetProperty(property);
                if (propertyInfo == null)
                {
                    return;
                }
                propertyInfo.SetValue(obj, value, null);
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("反射设置对象字段值异常 SetPropertyValue,obj:{0}\r\n property{1} \r\n value{2}", obj.ToString(), property, value), ex);
            }
        }

        #region 时间转换

        /// <summary>
        /// 字符串时间格式转日期时间统一字符格式
        /// 格式为:"yyyy-MM-dd"
        /// </summary>
        /// <param name="strDateTime"></param>
        /// <returns></returns>
        public static string ToDateString(this string strDateTime)
        {
            DateTime dt;
            var _isOk = DateTime.TryParse(strDateTime, out dt);
            if (_isOk == false)
            {
                return "";//  throw new Exception(string.Format("字符串转时间错误.字符串为:{0}", strDateTime));
            }
            return dt.ToDateString();
        }

        /// <summary>
        /// 获取格式化字符串，不带时分秒，格式："yyyy-MM-dd"
        /// </summary>
        /// <param name="dateTime">日期</param>
        public static string ToDateString(this DateTime dateTime)
        {
            return dateTime.ToString("yyyy-MM-dd");
        }

        /// <summary>
        /// 获取格式化字符串，不带时分秒，格式："yyyy-MM-dd"
        /// </summary>
        /// <param name="dateTime">日期</param>
        public static string ToDateString(this DateTime? dateTime)
        {
            if (dateTime == null)
                return string.Empty;
            return ToDateString(dateTime.Value);
        }

        /// <summary>
        /// 时间格式转字符串
        /// 字符串格式"yyyy-MM-dd HH:mm:ss.fff"
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string ToLongString(this DateTime dt)
        {
            return dt.ToString("yyyy-MM-dd HH:mm:ss.fff");
        }

        /// <summary>
        /// 字符串时间格式转时间统一字符格式
        /// 格式为:"yyyy-MM-dd HH:mm:ss.fff"
        /// </summary>
        /// <param name="strDateTime"></param>
        /// <returns></returns>
        public static string ToLongString(this string strDateTime)
        {
            DateTime dt;
            var _isOk = DateTime.TryParse(strDateTime, out dt);
            if (_isOk == false)
            {
                return "";// throw new Exception(string.Format("字符串转时间错误.字符串为:{0}", strDateTime));
            }
            return dt.ToString("yyyy-MM-dd HH:mm:ss.fff");
        }

        /// <summary>
        /// 字符串转时间格式
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static DateTime ToDateTime(this string dt)
        {
            DateTime result = DateTime.MinValue;
            DateTime.TryParse(dt, out result);
            return result;
        }

        #region 时间戳

        /// <summary>
        /// DateTime时间格式转换为Unix时间戳格式
        /// </summary>
        /// <param name="time"> DateTime时间格式</param>
        /// <returns>Unix时间戳格式</returns>
        public static string ToTimeStamp(this System.DateTime time)
        {
            return DateTime.Now.ToString("yyyyMMddhhmmssfff");
        }

        /// <summary>
        /// 时间戳转时间
        /// </summary>
        /// <param name="timeStamp">Unix时间戳</param>
        /// <returns></returns>
        public static DateTime TimeStampToTime(this string timeStamp)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp);
            TimeSpan toNow = new TimeSpan(lTime);
            return dtStart.Add(toNow);
        }

        #endregion 时间戳

        #endregion 时间转换

        #region DataTable 转换

        /// <summary>
        /// 转化一个DataTable
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <returns></returns>
        public static DataTable ListToDataTable<T>(this List<T> list)
        {
            //创建属性的集合
            List<PropertyInfo> pList = new List<PropertyInfo>();
            Type type = typeof(T);
            //获得反射的入口
            if (list != null && list.Any())
            {
                type = list.First().GetType();
            }
            else
            {
                return new DataTable();
            }

            DataTable dt = new DataTable();
            //把所有的public属性加入到集合 并添加DataTable的列
            Array.ForEach<PropertyInfo>(type.GetProperties(), p => { pList.Add(p); dt.Columns.Add(p.Name, p.PropertyType); });
            foreach (var item in list)
            {
                //创建一个DataRow实例
                DataRow row = dt.NewRow();
                //给row 赋值
                pList.ForEach(p => row[p.Name] = p.GetValue(item, null));
                //加入到DataTable
                dt.Rows.Add(row);
            }
            return dt;
        }

        #endregion DataTable 转换
    }
}